<?php

namespace App\Http\Controllers\applet_api;

use App\Http\Controllers\Controller;
use App\Models\AppOrder;
use App\Models\Information;
use App\Models\Node;
use Illuminate\Http\Request;

class OrderController extends Controller
{

    public function index(Request $Request)
    {
        $type = $Request->type ?: 'course';
        $limit = $Request->limit ?: 10;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;
        $sql = AppOrder::select('id','no','user_id','product_id','amount','type','coupon','integral','total_amount','pay_amount','pay_status','paid_at','payment_method','created_at')->where('pay_status','success')->where('type',$type)->where('user_id',$Request->uid);
        if($type == 'course'){
            $sql->with('course');
        }
        $total = $sql->count();
        $data = $sql->orderBy('id','desc')->get();
        
        
        $arr_id = [];
        foreach ($data as $k => $v) {
            $arr_id[] = $v->product_id;
        }

        $with = false;
        if($type == 'information'){
            $with = Information::select('id','title','img as cover','integral')->whereIn('id',$arr_id)->get();
        }

        if($type == 'node'){
            $with = Node::select('id','title','img as cover','integral')->whereIn('id',$arr_id)->get();
        }

        foreach ($data as $k => $v) {
            if($with){
                $data[$k]->course = $with->where('id',$v->product_id)->first();
            }
        }
        return response()->json(['code' => '200', 'msg' => 'success','total'=>$total,'data'=>$data]);
    }
    //生成订单
}
